import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { CommonService } from '../../../../services/common.service';
import { ToolsService } from '../../../../services/tools.service'
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';

interface DataItem {
  update_time: any;
  upload_time: any;
  file_size: any;
  status: any;
}
@Component({
  selector: 'app-contractextraction',
  templateUrl: './contractextraction.component.html',
  styleUrls: ['./contractextraction.component.css']
})
export class ContractextractionComponent implements OnInit {
  // 项目管理列表数据
  public listOfData: any = [
    {
      project_name: '',
      description: '',
      project_id: ''
    }
  ];
  // 新建项目数据
  public addListData: any = {
    project_name: '',
    description: ''
  }
  editId: string | null = null;
  editNameId: string | null = null;
  // 新建项目
  isVisible = false;
  // 删除的模态框
  deleteShow = false;
  // 点击删除拿到的id
  deleteId: '';
  // 测试model
  ceshimodel = false;
  // 描述编辑
  EditDescription: string = "";
  // 编辑名称
  EditName: string = "";
  // 导出返回的jobId
  jobId: '';
  // 剩余可创建项目
  ListLength: number = 0;
  //轮询定时器
  jobTimer: any = null
  //是否是从大到小
  isDesc = true;

  timeCompare = (a: DataItem, b: DataItem) => {
    return Date.parse(a.update_time) - Date.parse(b.update_time)
  };


  constructor(
    public http: CommonService,
    private router: Router,
    private message: NzMessageService,
    public changeDetectorRef: ChangeDetectorRef,
    public tools: ToolsService) { }
  ngOnInit(): void {
    // 获取项目列表数据
    this.getList()

  }

  ngOnDestroy(): void {
    //Called once, before the instance is destroyed.
    //Add 'implements OnDestroy' to the class.
    if (this.jobTimer != null) {
      clearInterval(this.jobTimer)
    }
  }
  // 获取项目列表数据
  getList() {
    this.http.get('/contract-extraction/project-mgr/query-all-project')
      .then((res: any) => {
        console.log(res)
        if(res && res.result != ''){
          this.listOfData = res.result
          // 剩余可创建项目数量
          let length = 100;
          this.ListLength = length
          if (this.ListLength === 100) {
            this.ListLength = this.ListLength - this.listOfData.length;
          }
          // this.SortList();
        }else{
          this.message.error("项目列表为空!")
        }
      }).catch((err: any) => {
        this.message.error(err.error_msg)
      })
  }
  // SortList() {
  //   if (!this.isDesc) {
  //     this.listOfData = this.listOfData.sort(function (a, b) {
  //       return Date.parse(a.update_time) - Date.parse(b.update_time); // 时间正序 从小到大
  //     });
  //   } else {
  //     this.listOfData = this.listOfData.sort(function (a, b) {
  //       console.log(Date.parse(b.update_time));
  //       return Date.parse(b.update_time) - Date.parse(a.update_time); // 时间倒叙 从大到小
  //     });
  //   }
  //   this.listOfData = [...this.listOfData];
  // }

  // changeSort() {
  //   this.isDesc = !this.isDesc;
  //   // this.SortList()
  // }


  //点击显示编辑名称input
  startNameEdit(data): void {
    this.editNameId = data.project_id;
    this.EditName = data.project_name;
    this.EditDescription = data.description;
    console.log(data)
  }
  // 编辑名称
  stopNameEdit(id) {
    this.editNameId = null;
    // 删除空格
    this.EditName= this.EditName.replace(/^\s+|\s+$/g,"")
    let newArray = this.listOfData.map(e => {
      if(e.project_id != id)
      return e.project_name
    });
    if (newArray.includes(this.EditName)) {
     this.message.error(this.EditName+'已经存在!');
     return;
    }
    if (this.EditName === '' ? this.message.error('项目名称输入框不能为空') : '') {
      return
    } else {
      this.http.post('/contract-extraction/project-mgr/update-project', {
        project_id: id,
        project_name: this.EditName,
        description: this.EditDescription
      }).then((res: any) => {
        console.log(res)
        this.getList()
      }).catch((err: any) => {
        this.message.error(err.error_msg)
      })
    }
  }
  //点击显示编辑描述input
  // startEdit(data): void {
  //   this.editId = data.project_id;
  //   this.EditDescription = data.description;
  //   this.EditName = data.project_name;
  //   console.log(data)
  //   console.log(this.editId)
  // }
  // 编辑描述
  // stopEdit(id, description): void {
  //   this.editId = null;
  //   let newArray = this.listOfData.map(e => {
  //     if(e.project_id != id)
  //     return e.e.description
  //   });
  //   if (newArray.includes(this.EditDescription)) {
  //    this.message.error(this.EditDescription+'已经存在!');
  //    return;
  //   }
  //     this.http.post('/contract-extraction/project-mgr/update-project', {
  //       project_id: id,
  //       project_name: this.EditName,
  //       description: this.EditDescription
  //     }).then((res: any) => {
  //       console.log(res)
  //       this.getList()
  //     }).catch((err: any) => {
  //       this.message.error(err.error_msg)
  //     })
  // }
  // 导出
  export(id) {
    // File.download('eyJkb2NfY29uZmlnIjoge30sICJleHRyYWN0X2NvbmZpZyI6IFtdfQQ==')
    //实例化
    // var file= new File();
    // //传入base64编码的字符串, 触发浏览器下载文件
    // file.download('eyJkb2NfY29uZmlnIjoge30sICJleHRyYWN0X2NvbmZpZyI6IFtdfQ==');

    this.http.post('/contract-extraction/project-mgr/export-project', {
      project_id: id
    }).then((res: any) => {
      console.log(res)
      this.jobId = res.result.job_id
      // job查询接口
      this.getJob()
    }).catch((err: any) => {
      this.message.error(err.error_msg)
    })
  }


  //**dataURL to blob** 
  dataURLtoBlob(dataurl) {
    // var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], 
    //     bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); 
    // while (n--) { 
    //     u8arr[n] = bstr.charCodeAt(n); 
    // } 
    // return new Blob([u8arr], { type: mime }); 
    const binaryString = window.atob(dataurl); //如果不使用base64，则注释这个
    const bytes = new Uint8Array(binaryString.length);
    return bytes.map((byte, i) => binaryString.charCodeAt(i));
  }

  createAndDownloadBlobFile(body, filename) {
    const blob = new Blob([body]);
    const fileName = `${filename}`;
    if (navigator.msSaveBlob) {
      // IE 10+
      navigator.msSaveBlob(blob, fileName);
    } else {
      const link = document.createElement('a');
      //支持HTML5下载属性的浏览器
      if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', fileName);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }
  }
  // job查询接口
  getJob() {
    let that = this;
    this.jobTimer = setInterval(function () {
      that.http.post('/contract-extraction/job-mgr/query-job', {
        job_id: that.jobId
      }).then((res: any) => {
        if (res.result) {
          if (res.result.job_status == "success") {
            let base64Pdf = res.result.job_result.file_base64;
            const arrayBuffer = that.dataURLtoBlob(base64Pdf); // 创建Array缓冲区
            that.createAndDownloadBlobFile(arrayBuffer, res.result.job_result.file_name);
            that.clearJobTimer();
          } else if (res.result.job_status == "waiting") {
            that.message.info(that.jobId + "正在排队等待，请稍后！");
          } else if (res.result.job_status == "running") {
            that.message.info(that.jobId + "正在导出，请稍后！");
          } else {
            that.message.error(that.jobId + "导出失败，请重试！");
            that.clearJobTimer();
          }
        }
        else {
          this.message.error(that.jobId + "导出失败，请重试！");
          that.clearJobTimer();
        }
      }).catch((data) => {
        this.message.error(that.jobId + "导出失败，请重试！");
        that.clearJobTimer();
      })

    }, 5000);


  }

  clearJobTimer() {
    if (this.jobTimer != null) {
      clearInterval(this.jobTimer)
    }
  }
  showModal(): void {
    this.isVisible = true;
    // 每次点击新建项目 清空输入框
    this.addListData.project_name = '';
    this.addListData.description = '';
  }

  handleOk(): void {
    this.isVisible = false;
  }

  handleCancel(): void {
    this.isVisible = false;
  }
  // 新建项目确定button
  addList(): void {
    // 删除空格
    this.addListData.project_name= this.addListData.project_name.replace(/^\s+|\s+$/g,"")
    this.addListData.description = this.addListData.description.replace(/^\s+|\s+$/g,"")
    let newArray = this.listOfData.map(e => e.project_name);
    if (newArray.includes(this.addListData.project_name)) {
     this.message.error(this.addListData.project_name + '已经存在!');
     return;
    }
    let newArrayTwo = this.listOfData.map(e => e.description);
    if (newArrayTwo.includes(this.addListData.description)) {
       this.message.error(this.addListData.description + '已经存在!');
       return;
    }
    if (this.addListData.project_name === '') {
      this.message.error('输入框名称不能为空!');
    } else {
      this.http.post('/contract-extraction/project-mgr/add-project', {
        project_name: this.addListData.project_name,
        description: this.addListData.description
      }).then((res: any) => {
          console.log(res)
          // 关闭modal框
          this.isVisible = false
          this.getList()
        }).catch((err: any) => {
          this.message.error(err.error_msg)
        })
    }

  }
  // 新建项目取消button
  quitList(): void {
    this.isVisible = false
  }
  // 删除按钮
  deleteData(e) {

    this.deleteShow = true;
    console.log(e)
    this.deleteId = e;
    console.log(this.deleteId + '拿到的id')
  }
  // 关闭删除模态框
  deleteshut() {
    this.deleteShow = false;
  }
  // 确认删除
  deleteOk() {
    console.log(this.deleteId + '确认拿到的id')
    this.http.post('/contract-extraction/project-mgr/delete-project', {
      project_id: this.deleteId
    }).then((res: any) => {
      console.log(res)
      this.getList()
      this.deleteShow = false;
    }).catch((err: any) => {
      this.message.error(err.error_msg)
    })
  }
  // 编辑 跳转路由 存储项目ID
  editItem(data) {
    this.router.navigateByUrl('/aicompetence/detail/data');
    sessionStorage.setItem('id', data.project_id);
    sessionStorage.setItem('name', data.project_name);
    // this.router.navigate(['/aicompetence/detail/data'],{
    //   queryParams:{
    //       name:data.project_name
    //   }
    // })
    console.log(data.project_name)
  }

  //时间格式化
  formatDate(data) {
    return this.tools.formatDate(data * 1000, "yyyy-MM-dd hh:mm:ss GMT+08:00")
  }
}
